package cn.com.api.service.impl;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ibm.icu.util.Calendar;

import cn.com.api.entity.ApiT_user_cash_records;
import cn.com.api.entity.ApiTmember;
import cn.com.api.entity.ApiU_advert;
import cn.com.api.entity.ApiU_bonus;
import cn.com.api.entity.ApiU_bonus_detail;
import cn.com.api.entity.ApiU_message;
import cn.com.api.mapper.ApiT_memberMapper;
import cn.com.api.mapper.ApiT_user_cash_recordsMapper;
import cn.com.api.mapper.ApiTmemberMapper;
import cn.com.api.mapper.ApiU_advertMapper;
import cn.com.api.mapper.ApiU_bonusMapper;
import cn.com.api.mapper.ApiU_bonus_detailMapper;
import cn.com.api.mapper.ApiU_messageMapper;
import cn.com.api.service.ApiU_bonus_detailService;
import cn.com.api.service.impl.base.U_bonus_detailServiceImplBase;
import cn.com.util.DateUtil;
import cn.com.util.HongBaoAlgorithm;
import cn.com.util.PageInfo;
import cn.com.util.RedPacketUtil;
import cn.com.util.Util;

/**
 * 
 **/
@Service
public class ApiU_bonus_detailServiceImpl extends U_bonus_detailServiceImplBase implements ApiU_bonus_detailService {
	@Autowired
	private ApiU_bonus_detailMapper apiU_bonus_detailMapper;
	@Autowired
	private ApiU_bonusMapper apiU_bonusMapper;
	@Autowired
	private ApiU_advertMapper apiU_advertMapper;
	@Autowired
	private ApiT_user_cash_recordsMapper apiT_user_cash_recordsMapper;
	@Autowired
	private ApiTmemberMapper apiTmemberMapper;
	@Autowired
	private ApiU_messageMapper apiU_messageMapper;

	@Override
	public ApiU_bonus_detail OpenBonusItem(String bonus_id, ApiTmember tmember, String get_type) {
		ApiU_bonus_detail b_detail = new ApiU_bonus_detail();

		ApiU_bonus bonus = this.apiU_bonusMapper.findU_bonusById(Integer.valueOf(bonus_id));
		b_detail.setBless_word(bonus.getBless_word());

		String retString = this.apiU_bonus_detailMapper.checkHasMoneyBonus(bonus_id);
		String[] rets = retString.split(":");// 领取的有钱红包数:已领总金额
		if (rets.length != 2) {
			return null;
		}
		// 红包金额算法？？？？？？？
		// public static float generate(long total, int count, long max, long
		// min, int usedCount, long usedMoney)

		long total = Long.parseLong("" + Math.round(bonus.getSummy().floatValue() * 100));
		int count = bonus.getCount_charge();
		long max = Long.parseLong("" + Math.round(bonus.getMax_money().floatValue() * 100));
		long min = Long.parseLong("" + Math.round(bonus.getMin_money().floatValue() * 100));
		int usedCount = Integer.valueOf(rets[0]);
		long usedMoney = Long.parseLong("" + Math.round((Float.valueOf(rets[1])) * 100));

		long avabileMoney = total - usedMoney;
		int avabileCount = count - usedCount;
		double times = (double) (Math.round(max * count / total));
		// double times = 2.1;

		if (usedCount < count) {
			// float money = HongBaoAlgorithm.generate( total, count, max, min,
			// usedCount, usedMoney);
			float money = RedPacketUtil.generate(avabileMoney, avabileCount, max, min, times);
			b_detail.setBonus_id(bonus_id);
			b_detail.setGet_time(Util.CurrentTime());
			b_detail.setGet_uhead(tmember.getCavatar());
			b_detail.setGet_uid(tmember.getCid().toString());
			b_detail.setGet_uname(tmember.getCnick());
			b_detail.setStatus(1);
			b_detail.setMoney(new BigDecimal(money + ""));
			b_detail.setGet_type(Integer.valueOf(get_type));
			this.apiU_bonus_detailMapper.U_bonus_detailInsertion(b_detail);

			// 更新最佳手气
			if ((count - usedCount) == 1) {
				ApiU_bonus_detail max_detail = this.apiU_bonus_detailMapper.getMaxMoneybyBonusId(bonus_id);
				max_detail.setIs_max(1);
				this.apiU_bonus_detailMapper.updateU_bonus_detail(max_detail);
			}

			// 领取红包后在金额记录表中记录，修改余额
			ApiT_user_cash_records apiT_user_cash_records = new ApiT_user_cash_records();
			apiT_user_cash_records.setUser_id(tmember.getCid().toString());
			apiT_user_cash_records.setCate_type(1);
			apiT_user_cash_records.setCreate_time(DateUtil.nowTimeToString());
			apiT_user_cash_records.setMoney(new BigDecimal(money + ""));
			apiT_user_cash_records.setRemark("收到的红包");
			apiT_user_cash_records.setProcess_type(0);// 是收入还是支出
			apiT_user_cash_recordsMapper.T_user_cash_recordsInsertion(apiT_user_cash_records);
			// 更新T_member余额字段
			BigDecimal cmoney = new BigDecimal(tmember.getCmoney().toString());
			tmember.setCmoney(cmoney.add(new BigDecimal(money + "")));
			this.apiTmemberMapper.updateApiTmember(tmember);
			// 消息
			ApiU_message message = new ApiU_message();
			message.setAdd_time(DateUtil.nowTimeToString());
			message.setConn_id(b_detail.getId());
			message.setTitle("红包");
			message.setType(4);
			message.setUser_id(tmember.getCid().toString());
			message.setIs_read(0);
			message.setContent("您已领取了一个金额为：" + new BigDecimal(money + "") + " 元的红包");
			apiU_messageMapper.U_messageInsertion(message);
		} else {// 有金额的已被领完
			Integer ret = this.apiU_bonus_detailMapper.checkBonusAvailable(bonus_id);
			if (ret == 1) {
				b_detail.setBonus_id(bonus_id);
				b_detail.setGet_time(Util.CurrentTime());
				b_detail.setGet_uhead(tmember.getCavatar());
				b_detail.setGet_uid(tmember.getCid().toString());
				b_detail.setGet_uname(tmember.getCnick());
				b_detail.setStatus(1);
				b_detail.setMoney(new BigDecimal(0));
				b_detail.setGet_type(Integer.valueOf(get_type));
				this.apiU_bonus_detailMapper.U_bonus_detailInsertion(b_detail);
			} else {
				// 总红包数被领完了，更新红包所属广告状态为【关闭】
				ApiU_advert advert = apiU_advertMapper.findBonusAdvertByBonusID(bonus_id);
				if (!Util.isNull(advert)) {
					advert.setStatus(2);
					apiU_advertMapper.updateU_advert(advert);
				}
				bonus.setIs_expire(2); // 已领完
				apiU_bonusMapper.updateU_bonus(bonus);
			}
		}
		return b_detail;
	}

	@Override
	public ApiU_bonus_detail ForwardBonusItem(String bonus_id, ApiTmember tmember, String forwardWord,
			String get_type) {
		ApiU_bonus_detail b_detail = new ApiU_bonus_detail();
		// 计算红包金额
		ApiU_bonus bonus = this.apiU_bonusMapper.findU_bonusById(Integer.valueOf(bonus_id));
		b_detail.setBless_word(bonus.getBless_word());

		String retString = this.apiU_bonus_detailMapper.checkHasMoneyBonus(bonus_id);
		String[] rets = retString.split(":");
		if (rets.length != 2) {
			return null;
		}
		// 红包金额算法？？？？？？？
		// public static float generate(long total, int count, long max, long
		// min, int usedCount, long usedMoney)
		long total = (long) (bonus.getSummy().floatValue() * 100);
		int count = bonus.getCount_charge();
		long max = (long) (bonus.getMax_money().floatValue() * 100);
		long min = (long) (bonus.getMin_money().floatValue() * 100);
		int usedCount = Integer.valueOf(rets[0]);
		long usedMoney = (long) (Float.parseFloat(rets[1]) * 100);

		if (usedCount < count) {
			float money = HongBaoAlgorithm.generate(total, count, max, min, usedCount, usedMoney);
			b_detail.setBonus_id(bonus_id);
			b_detail.setGet_time(Util.CurrentTime());
			b_detail.setGet_uhead(tmember.getCavatar());
			b_detail.setGet_uid(tmember.getCid().toString());
			b_detail.setGet_uname(tmember.getCnick());
			b_detail.setIs_forward(1);
			b_detail.setForward_word(forwardWord);
			b_detail.setMoney(new BigDecimal(money));
			b_detail.setGet_type(Integer.valueOf(get_type));
			this.apiU_bonus_detailMapper.U_bonus_detailInsertion(b_detail);
		} else {// 有金额的已被领完
			Integer ret = this.apiU_bonus_detailMapper.checkBonusAvailable(bonus_id);
			if (ret == 1) {
				b_detail.setBonus_id(bonus_id);
				b_detail.setGet_time(Util.CurrentTime());
				b_detail.setGet_uhead(tmember.getCavatar());
				b_detail.setGet_uid(tmember.getCid().toString());
				b_detail.setGet_uname(tmember.getCnick());
				b_detail.setIs_forward(1);
				b_detail.setForward_word(forwardWord);
				b_detail.setMoney(new BigDecimal(0));
				b_detail.setGet_type(Integer.valueOf(get_type));
				this.apiU_bonus_detailMapper.U_bonus_detailInsertion(b_detail);
			} else {
				// 总红包数被领完了，更新红包所属广告状态为【关闭】
				ApiU_advert advert = apiU_advertMapper.findBonusAdvertByBonusID(bonus_id);
				advert.setStatus(2);
				apiU_advertMapper.updateU_advert(advert);
			}
		}
		return b_detail;
	}

	// @Override
	// public ApiU_bonus_detail forwardBonusDetail(Integer bonus_detail_id,
	// String forward_word)
	// {
	// ApiU_bonus_detail b_detail =
	// apiU_bonus_detailMapper.getBonus_detailByID(bonus_detail_id);
	// if(b_detail != null)
	// {
	// b_detail.setIs_forward(1);
	// b_detail.setForward_word(forward_word);
	// apiU_bonus_detailMapper.updateU_bonus_detail(b_detail);
	// }
	// return b_detail;
	// }

	@Override
	public ApiU_bonus getBonus_ByDetailID(Integer bonus_detail_id) {
		ApiU_bonus bonus = new ApiU_bonus();
		ApiU_bonus_detail b_detail = apiU_bonus_detailMapper.getBonus_detailByID(bonus_detail_id);
		if (!Util.isNull(b_detail)) {
			bonus = apiU_bonusMapper.findU_bonusByID(Integer.valueOf(b_detail.getBonus_id()));
			bonus.setBless_word(b_detail.getForward_word());
			List<ApiU_bonus_detail> detail_list = new ArrayList<ApiU_bonus_detail>();
			detail_list.add(b_detail);
			bonus.setBonus_details(detail_list);
		}
		return bonus;
	}

	@Override
	public ApiU_bonus_detail openBonus_detailByID(String bonus_detail_id, ApiTmember tmember) {
		ApiU_bonus_detail b_detail = apiU_bonus_detailMapper.findU_bonus_detailById(Integer.valueOf(bonus_detail_id));
		if (!Util.isNull(b_detail)) {
			if (b_detail.getStatus() == 1) {

			} else {
				String fromuserid = b_detail.getGet_uid();// 谁转发的
				Date now = new Date();
				SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
				b_detail.setGet_time(dateFormat.format(now));
				b_detail.setGet_uid(tmember.getCid().toString());
				b_detail.setGet_uname(tmember.getCnick());
				b_detail.setGet_uhead(tmember.getCavatar());
				b_detail.setStatus(1);
				apiU_bonus_detailMapper.updateU_bonus_detail(b_detail);

				// 领取红包后在金额记录表中记录，修改余额
				ApiT_user_cash_records apiT_user_cash_records = new ApiT_user_cash_records();
				apiT_user_cash_records.setUser_id(tmember.getCid().toString());
				apiT_user_cash_records.setCate_type(1);
				apiT_user_cash_records.setCreate_time(DateUtil.nowTimeToString());
				apiT_user_cash_records.setMoney(new BigDecimal(b_detail.getMoney() + ""));
				apiT_user_cash_records.setRemark("红包广告");
				apiT_user_cash_records.setProcess_type(0);// 是收入还是支出
				apiT_user_cash_recordsMapper.T_user_cash_recordsInsertion(apiT_user_cash_records);
				// 更新T_member余额字段
				BigDecimal cmoney = new BigDecimal(tmember.getCmoney().toString());
				tmember.setCmoney(cmoney.add(new BigDecimal(b_detail.getMoney() + "")));
				this.apiTmemberMapper.updateApiTmember(tmember);
				// 消息
				List<ApiU_message> list = new ArrayList<ApiU_message>();
				ApiU_message message = new ApiU_message();
				message.setAdd_time(DateUtil.nowTimeToString());
				message.setConn_id(b_detail.getId());
				message.setTitle("红包");
				message.setType(4);
				message.setUser_id(tmember.getCid().toString());
				message.setIs_read(0);
				message.setContent("您已领取了一个金额为：" + new BigDecimal(b_detail.getMoney() + "") + " 元的红包");
				list.add(message);
				ApiU_message message2 = new ApiU_message();
				message2.setAdd_time(DateUtil.nowTimeToString());
				message2.setConn_id(b_detail.getId());
				message2.setTitle("红包");
				message2.setType(4);
				message2.setUser_id(fromuserid);
				message2.setIs_read(0);
				message2.setContent(tmember.getCnick() + " 领取了你的转发的红包");
				list.add(message2);
				apiU_messageMapper.insertmessageList(list);
			}
		}
		return b_detail;
	}

	public void inserts(Map map) {
		apiU_bonus_detailMapper.selectForHome(map);
	}

	public void insertU_bonus_details(Map map) {
		apiU_bonus_detailMapper.insertU_bonus_details(map);
	}

	@Override
	public ApiU_bonus_detail checkAvailableBonus(String bonus_id, String user_id) {
		return this.apiU_bonus_detailMapper.checkAvailableBonus(bonus_id, user_id);
	}

	@Override
	public List<ApiU_bonus_detail> getRollBonusListPage(String type) {
		PageInfo page = new PageInfo();
		page.setCurrentPage(1);
		page.setShowCount(30);
		List<ApiU_bonus_detail> b_details = this.apiU_bonus_detailMapper.getRollBonusListPage(type, page);
		for (ApiU_bonus_detail detail : b_details) {
			// +00 10:27:32.000000
			String timeString = detail.getTime_range();
			String[] times = timeString.split(" ");
			String dayString = times[0];
			String hoursString = times[1];
			String[] timeStrings = hoursString.split(":");
			if (Integer.valueOf(dayString) > 0) {
				detail.setTime_range(Integer.valueOf(dayString) + "天前");
			} else if (Integer.valueOf(timeStrings[0]) > 0) {
				detail.setTime_range(Integer.valueOf(timeStrings[0]) + "小时前");
			} else if (Integer.valueOf(timeStrings[1]) > 0) {
				detail.setTime_range(Integer.valueOf(timeStrings[1]) + "分钟前");
			} else {
				detail.setTime_range("刚刚");
			}
		}
		return b_details;
	}

	// 红包排行榜
	public List<ApiU_bonus_detail> getBounusRankingList(Map map, String type, PageInfo page) {
		String begin_time = "";
		String end_time = "";
		if (!Util.isNull(type)) {
			if (type.equals("1"))// 小时榜
			{
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
				Date dt = new Date();
				end_time = sdf.format(dt);
				Calendar rightNow = Calendar.getInstance();
				rightNow.setTime(dt);
				rightNow.add(Calendar.HOUR, -1);// 当前日期加1小时
				begin_time = sdf.format(rightNow.getTime());
			} else if (type.equals("2")) {// 昨日榜
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Date dt = new Date();
				Calendar rightNow = Calendar.getInstance();
				rightNow.setTime(dt);
				rightNow.add(Calendar.DAY_OF_MONTH, -1);// 当前日期减1天
				begin_time = sdf.format(rightNow.getTime()) + " 00:00:00";
				end_time = sdf.format(rightNow.getTime()) + " 23:59:59";
			} else if (type.equals("3")) {// 前日榜
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				Date dt = new Date();
				Calendar rightNow = Calendar.getInstance();
				rightNow.setTime(dt);
				rightNow.add(Calendar.DAY_OF_MONTH, -2);// 当前日期减2天
				begin_time = sdf.format(rightNow.getTime()) + " 00:00:00";
				end_time = sdf.format(rightNow.getTime()) + " 23:59:59";
			}
		}
		if (!begin_time.equals("")) {
			map.put("begin_time", begin_time);
			map.put("end_time", end_time);
		}
		return this.apiU_bonus_detailMapper.getBonusHoldListPage(map, page);
	}
	
	//收到的红包 头部
	public String getReceiveNormalBonusListHeader(String user_id)
	{
		return this.apiU_bonus_detailMapper.getReceiveNormalBonusListHeader(user_id);
	}
	
	//收到的红包列表
	public List<ApiU_bonus_detail> getReceiveNormalBonusList(String user_id, PageInfo page)
	{
		return this.apiU_bonus_detailMapper.getReceiveNormalBonusListPage(user_id, page);
	}
	
	//发出的红包 头部
	public String getSendNormalBonusListHeader(String user_id)
	{
		return this.apiU_bonus_detailMapper.getSendNormalBonusListHeader(user_id);
	}
}
